import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import {Table, Button,Row,Col,Layout, Breadcrumb,Menu,Dropdown,Popconfirm,Icon,Input,Card,Spin,Pagination,message,Tabs,Modal,Select,Form} from 'antd';
import style from '../../styles/TableCss.less';
import {Link} from 'dva/router'
import Reset from '../../styles/ResetInput.less';
import InStyle from '../../styles/Info.less'
import reqwest from 'reqwest';
import draftToMarkdown from 'draftjs-to-markdown';
import draftToHtml from 'draftjs-to-html';
import {reqwest_post} from '../../utils/Reqwest.js'
// import {load_server} from '../../utils/Clue.js'
import { Editor } from 'react-draft-wysiwyg'
import {datevali_deta} from '../../utils/Validator.js'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
const {  Content, Footer } = Layout;
const TabPane = Tabs.TabPane;
const ButtonGroup = Button.Group;
const Option = Select.Option;
class Clue extends React.Component{
  constructor(props){
    super(props);
    this.state={
      data:[],
      dropDown:'所有线索',
      list:[],
      visibled:false,
      visibled1:false,
      selectedRowKeys:[],
      pagination:[],
      record:undefined,
      tab:'1',
      assign:[],
      user_id:null,
      contentState:'',
      page:1,
      columns:[{
        title:'姓名',
        dataIndex:'name',
        width:'20%'
      },{
        title:'手机号码',
        dataIndex:'mobile',
      },{
        title:'被指派人',
        dataIndex:'assign_user_name',
      },{
        title:'地址',
        dataIndex:'address',
      },{
        title:'操作',
        key:'action',
        render:(text,record) => (
          <span>
            <Link to={{pathname:'/app/newor',query:{current:this.props.location.query.current*1-1,state:'创建','id':record.key,name:record.name,mobile:record.mobile}}}>下单</Link>
            <span className="ant-divider" />
            <Link onClick={()=>{window.localStorage['clues']=JSON.stringify(record)}} to={{pathname:'/app/editclue',query:{ims:record.key,state:'编辑','current':this.props.location.query.current,name:record.name,mobile:record.mobile,address:record.address,remark:record.remark}}}>编辑</Link>
            <span className="ant-divider" />
            <a onClick={()=>this.setState({record:record,visibled1:true})}>备注</a>
            <span className="ant-divider" />
            <Popconfirm title="确认删除吗?" onConfirm={(e) => this.onDelete(record.key, e,this)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      }],
      _columns:[{
        title:'姓名',
        dataIndex:'name',
        width:'20%'
      },{
        title:'手机号码',
        dataIndex:'mobile',
      },{
        title:'地址',
        dataIndex:'address',
      },{
        title:'操作',
        key:'action',
        render:(text,record) => (
          <span>
            <Link to={{pathname:'/app/newor',query:{current:this.props.location.query.current*1-1,state:'创建','id':record.key,name:record.name,mobile:record.mobile}}}>下单</Link>
            <span className="ant-divider" />
            <Link to={{pathname:'/app/editclue',query:{ims:record.key,state:'编辑','current':this.props.location.query.current,name:record.name,mobile:record.mobile,address:record.address,remark:record.remark}}}>编辑</Link>
          </span>
        )
      }]
    }
  }
  onDelete(key,e,_this){
    const data = _this.state.data.filter(item => item.key !== key);
    // _this.setState({data });
    reqwest({
      url: window.host+'/api/clues/'+key,
      method: 'delete',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        // access_token:'1D34Z4i+CRE5DkYEBrpbhrigA+QU2lzIwEVqALrVmhQnPXO/THJGQvAPhLkwjO6U/czFYRNBoSwE9k8EQEA3RQ==',
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      // const pagination = { ...this.state.pagination };
      _this.fetch(this.state.pagination.total);
      if(data.status=='success'){
        message.success('删除成功',0.6)
      }else{
        message.error(data.msg,0.4)
      }
    });
  }
  fetch (params = {}) {
    console.log('params:', params);
    let _data=[];
    let _tab = null;
    console.log(this.state.tab)
    // return;
    this.setState({ loading: true });
    this.state.tab==='1'||params.tab==="1"?_tab={
      access_token:localStorage['token'],
      page:params.current,
    }:_tab={
      access_token:localStorage['token'],
      page:params.current,
      type:'assign'
    }
    reqwest({
      url: window.host+'/api/clues',
      method: 'get',
      crossOrigin: true,
      data:_tab,
      type: 'json',
    }).then((data) => {
      console.log(data);
        const pagination = { ...this.state.pagination };
        pagination.total = data.total;
        for(let i of data.list){
          // console.log(i.remark)
          _data.push({
            key:i.id,
            ID:i.id,
            name:i.name,
            mobile:i.mobile,
            address:i.address,
            assign_user_name:i.assign_user_name,
            remark:i.remark,
            // description:<p>{i.remark==null||i.remark==undefined||i.remark=='null'?i.remark:JSON.parse(i.remark).blocks[0].text}</p>
          })
      }
      if(data.status=='success'){
        this.setState({
          loading: false,
          data: _data,
          assign:data.assign_users,
          list:data.list,
          pagination:pagination,
        });
      }
    }).fail( (err, msg) =>{
       console.log(1)
    })
  }
  assignUserClue(){
    // load_server('/api/clues/assign','post',{access_token:localStorage['token'],clue_ids:clues_ids,assign_user_id:user_id})
    const {selectedRowKeys,user_id} = this.state;
    if(selectedRowKeys.length<1){message.warning('并没有选中任何线索',0.6);this.setState({visibled:false});return;}
    let _this = this;
    reqwest({
      url: window.host+'/api/clues/assign',
      method: 'post',
      crossOrigin: true,
      data:{access_token:localStorage['token'],clue_ids:selectedRowKeys,assign_user_id:user_id},
      type: 'json'
    }).then((data)=>{
      if(data.status=='success'){
        message.success('指派成功',0.6);
        _this.setState({visibled:false});
      }
    }).fail((data)=>{
      message.error('网络连接失败',0.6);
    })
  }
  componentWillMount(){
    this.fetch({current:1,tab:1});
    // console.log(this.props.location.current)
  }
  handleTabClick(e){
    console.log(e)
    // this.setState({tab:e});
    this.state.tab=e
    this.fetch({current:1,tab:e})
  }
  menuClick(e){
    // console.log(e.item.props.value)
    this.setState({dropDown:e.item.props.value});
  }
  onSelectChange(selectedRowKeys){
    // console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  }
  addRemarks(record){
    // console.log(recoco)
    // return
    let _this=this;
    const {contentState} =this.state;
    let _date = new Date();
    this.props.form.validateFields((err, values) => {
      console.log(values.remark)
      values.remark.date=datevali_deta(_date);
      values.remark.name=JSON.parse(window.localStorage['setting']).name;
      reqwest_post('/api/clues/add_remark',{
        access_token:window.localStorage['token'],
        id:_this.state.record.key,
        remark:"~"+JSON.stringify(values.remark),
      },(data)=>{
        if(data.status=='success'){
          message.success('更新成功',1);
        }else{
          message.error(data.msg,1)
        }
      })
      _this.setState({visibled1:false});
    });
    // return;

  }
  onContentStateChange(contentState){
    this.setState({
      contentState
    });
  }
  getExplorer(){
    let explorer = window.navigator.userAgent ;
      //ie
      if (explorer.indexOf("MSIE") >= 0) {
          return 'ie';
      }
      //firefox
      else if (explorer.indexOf("Firefox") >= 0) {
          return 'Firefox';
      }
      //Chrome
      else if(explorer.indexOf("Chrome") >= 0){
          return 'Chrome';
      }
      //Opera
      else if(explorer.indexOf("Opera") >= 0){
          return 'Opera';
      }
      //Safari
      else if(explorer.indexOf("Safari") >= 0){
          return 'Safari';
      }
  }
  handleExcel(){
    if(getExplorer()=='ie'){
      var curTbl = document.getElementById(tableid);
      var oXL = new ActiveXObject("Excel.Application");

      //创建AX对象excel
      var oWB = oXL.Workbooks.Add();
      //获取workbook对象
      var xlsheet = oWB.Worksheets(1);
      //激活当前sheet
      var sel = document.body.createTextRange();
      sel.moveToElementText(curTbl);
      //把表格中的内容移到TextRange中
      sel.select();
      //全选TextRange中内容
      sel.execCommand("Copy");
      //复制TextRange中内容
      xlsheet.Paste();
      //粘贴到活动的EXCEL中
      oXL.Visible = true;
      //设置excel可见属性

      try {
          var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
      } catch (e) {
          print("Nested catch caught " + e);
      } finally {
          oWB.SaveAs(fname);

          oWB.Close(savechanges = false);
          //xls.visible = false;
          oXL.Quit();
          oXL = null;
          //结束excel进程，退出完成
          //window.setInterval("Cleanup();",1);
          // let idTmr = window.setInterval("Cleanup();", 1);

      }
    }else{
      this.tableToExcel(tableid)
    }
  }
  handleToExcel(){
    var uri = 'data:application/vnd.ms-excel;base64,',
    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="Content-Type" charset=utf-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
      base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) },
      format = function(s, c) {
          return s.replace(/{(\w+)}/g,
          function(m, p) { return c[p]; }) }
      return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
      window.location.href = uri + base64(format(template, ctx))
    }

  }
  render(){
    let _record,_reNode;
    const { selectedRowKeys,data,pagination,loading,dropDown,columns,list,assign } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
    };
    const assing_select = assign.map(function(data){
      return <Option key={''+data.id} value={''+data.id}>{data.name}</Option>
    })
    const formItemLayout = {
      labelCol: { span: 4},
      wrapperCol: { span: 17 },
      style:{minWidth:200}
    };
    const _card = list.map(function(data){
      return <Card  className={`${InStyle.card_list}`} key={data.id}>
        <i >{data.name}</i>
        <i >{data.mobile}</i>
        <i >
          <Link to={{pathname:'/app/deaor',query:{wudi:JSON.stringify(data),ma:'/app/newclue'}}}>详情</Link>
        </i>
      </Card>
    })
    // console.log(draftToHtml(this.state.record))
    if(this.state.record===undefined){
      _record=undefined
    }else if(this.state.record.remark==null||this.state.record.remark=='null'){
      _record=['']
    }else{
      _record=this.state.record.remark.split('~');
    }

    console.log(_record)
    const {getFieldDecorator}=this.props.form;
      // <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/">所有客户</a>
    const customerMemu=(
      <Menu onClick={this.menuClick.bind(this) } selectedKeys={[dropDown]}>
        <Menu.Item value='所有线索'>
          <a target="_blank" rel="noopener noreferrer">所有线索</a>
        </Menu.Item>
        <Menu.Item value='我的线索'>
          <a target="_blank" rel="noopener noreferrer" >我的线索</a>
        </Menu.Item>
        <Menu.Item value='aaaa'>
          <a target="_blank" rel="noopener noreferrer">aaaa</a>
        </Menu.Item>
      </Menu>
    )
    // let _node =this.state.record==undefined?null:draftToHtml(JSON.parse(this.state.record.remark))
    // debugger
    // console.log(_record)
    // if(this.state.record.remark!=='null'){
    //   debugger
    //   _record=this.state.record.remark
    // }
    return(
      <Layout style={{background:'#fff', height:'100%'}}>
        <Content >
          <Row type='flex'>
            <Col  sm={{span:7,offset:0}} xs={{span:9}} style={{padding:'24px 25px 0px'}}>
              <Breadcrumb style={{fontSize:14}}>
                <Breadcrumb.Item>线索管理</Breadcrumb.Item>
              </Breadcrumb>
            </Col>
            <Col xl={{span :3,offset:13}} lg={{span:3,offset:13}} md={{span:3,offset:13}} sm={{span:3,offset:13}} xs={{span:2,offset:8}} style={{lineHeight:'60px',textAlign:'right'}}>
              <Button ><Link to={{pathname:'/app/newclue',query:{state:'新建',current:this.props.location.query.current}}}>新建线索</Link></Button>
            </Col>
          </Row>
          <Layout className={`${style.tb_serbor}`}>
            <Row type='flex' className={`${style.tb_ser}`}>
              <Col sm={{span:7}} xs={{span:0}}>

              </Col>
              <Col sm={{span:7,offset:10}} xs={{span:14,offset:10}} style={{textAlign:'right'}}>

              </Col>
            </Row>
            <Tabs onTabClick={(e)=>{this.handleTabClick(e)}} defaultActiveKey="1" activeKey={this.state.tab} >
              <TabPane tab="我的" key="1">
                <ButtonGroup style={{marginBottom:15}}>
                  <Button  onClick={()=>this.setState({visibled:true})} >批量指派</Button>
                </ButtonGroup>
                <Table columns={columns}
                  dataSource={data}
                  id="table_clue"
                  rowKey="table_clue"
                  className="table_clue"
                  pagination={pagination}
                  loading={loading}
                  rowSelection={rowSelection}
                  onChange={this.fetch.bind(this)}
                />
              </TabPane>
              <TabPane tab="指派给我" key="2">
                <Table columns={this.state._columns}
                  dataSource={data}
                  pagination={pagination}
                  loading={loading}
                  onChange={this.fetch.bind(this)}
                />
              </TabPane>
            </Tabs>
          </Layout>
        </Content>
        {this.state.record==undefined?null:<Modal refs='remark' title='备注' onCancel={()=>{this.setState({visibled1:false})}} visible={this.state.visibled1} onOk={this.addRemarks.bind(this)}>
          <Row style={{maxHeight:300,overflow:'auto'}}>{_record[0]===''?null:_record.map((data,index,obj)=>{
            // console.log(data.length)
            // console.log(this.state.record.remark==='null'||this.state.record.remark==="")
            return <p className={`${InStyle.remark_list}`}  key={index}>
              {JSON.parse(data).blocks.map((dats)=>{
                console.log(dats)
                return <span key={dats.key} className={`${Reset.reset_remark}`} key={dats.key}><span>{dats.text}</span></span>
              })}
              <span style={{textAlign:'right',display:'block'}}>{JSON.parse(data).date}</span>
            </p>

            // return
            // return <p className={`${Reset.reset_remark}`} key={data.key}><span>{data.text}</span></p>
          })}
          </Row>
          <Row >
            <Form.Item  label='备注'>
                {getFieldDecorator('remark',{
                  initialValue:undefined,
                })(
                  <Editor onContentStateChange={()=>this.onContentStateChange} contentState={this.state.contentState}  toolbarHidden editorClassName={`${style.reset_editor}`} editorStyle={{fontSize:12,margin:0,height:'auto'}} wrapperStyle={{border:'1px solid #cecece',borderRadius:4,width:'100%',minHeight:100}} />
                )}
              </Form.Item>
          </Row>
        </Modal>}
        <Modal title='批量指派' onCancel={()=>{this.setState({visibled:false})}} visible={this.state.visibled} onOk={this.assignUserClue.bind(this)}>
          <Select style={{minWidth:200}}  className={`${Reset.ncc_reset_border}`} onChange={(e)=>{this.setState({user_id:e})}} placeholder="批量指派" optionFilterProp='children' showSearch>
           {assing_select}
         </Select>
        </Modal>
      </Layout>
    )
  }
}
// {this.state.record.remark.split('~').map((data,index,obj)=>{
          //   console.log(data)
          //   return
          //   // return <p className={`${Reset.reset_remark}`} key={data.key}><span>{data.text}</span></p>
          // })}
// <Input.Search
                //   placeholder="input search text"
                //   onSearch={value => console.log(value)}
                //  />
// <Dropdown className={`${style.dropDown}`}  overlay={customerMemu} >
                  // <a className={`${style.customerDown}`}>
                    // {dropDown} <Icon type="down" />
                  // </a>
                // </Dropdown>
                // <Spin spinning={loading}>
              // <div className={`${InStyle.card_content}`}>
                // <Card className={`${InStyle.card_list}`} key={data.key}>
                  // <i >姓名</i>
                  // <i >手机</i>
                  // <i >操作 </i>
                // </Card>
                // {_card}
              // </div>
              // <Pagination className={`${InStyle.page}`} onChange={this.fetch.bind(this)} total={pagination} />
            // </Spin>
const ClueForm = Form.create()(Clue);
export default connect()(ClueForm);
